package com.enki.adminplatform.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.enki.adminplatform.common.Result;
import com.enki.adminplatform.common.ResultCodeEnum;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author yinyin
 * @create 2021/07/27 下午 4:11
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    //处理登录失败   返回自己定义的Result对象
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setContentType("application/json;charest=UTF-8");
        ServletOutputStream outputStream= response.getOutputStream();

        Result result= Result.error().message(e.getMessage());
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }
}
